<?php


namespace app\api\controller\v1;
use app\lib\resolution\Layzz;
use app\lib\resolution\Vnil;
use app\lib\resolution\Whosecard;
use think\facade\Request;

class Resolution
{
    public function location()
    {
        $sUrl = Request::get('url');
        $sUrl = str_replace("https","http",$sUrl);
        $oCurl = curl_init();
        // 设置请求头, 有时候需要,有时候不用,看请求网址是否有对应的要求
        $header[] = "Content-type: application/x-www-form-urlencoded";
        $user_agent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36";
        curl_setopt($oCurl, CURLOPT_URL, $sUrl);
        curl_setopt($oCurl, CURLOPT_HTTPHEADER,$header);
        // 返回 response_header, 该选项非常重要,如果不为 true, 只会获得响应的正文
        curl_setopt($oCurl, CURLOPT_HEADER, true);
        // 是否不需要响应的正文,为了节省带宽及时间,在只需要响应头的情况下可以不要正文
        curl_setopt($oCurl, CURLOPT_NOBODY, true);
        // 使用上面定义的 ua
        curl_setopt($oCurl, CURLOPT_USERAGENT,$user_agent);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        // 不用 POST 方式请求, 意思就是通过 GET 请求
        curl_setopt($oCurl, CURLOPT_POST, false);
        $sContent = curl_exec($oCurl);
        // 获得响应结果里的：头大小
        $headerSize = curl_getinfo($oCurl, CURLINFO_HEADER_SIZE);
        // 根据头大小去获取头信息内容
        $header = substr($sContent, 0, $headerSize);
        curl_close($oCurl);
        try{
            preg_match('/Location: (.*?)\r\n/i',$header,$match);
            return writeJson(200,$match[1]);

        }catch (\Exception $e){
            return writeJson(400,[]);
        }
    }

    public function xhs(){
        $link = Request::get('link') ?? "";
        $content = (new Layzz())->getDetail($link);
        $result = json_decode($content,true);
        return writeJson(200,$result);
    }

    public function third_xhs(){
        $link = Request::get('link') ?? "";
        $content = (new Layzz())->third_getDetail($link);
        echo $content;
//        $result = json_decode($content,true);
//        dump($result);
//        return writeJson(200,$content);
    }


    public function xhsDetail(){
        $short_url = Request::get('short_url') ?? "";
        $content = (new Whosecard())->getDetail($short_url);
        $result = json_decode($content,true);
        return writeJson(200,$result);
    }


    public function getVnilRealUrl(Request $request){
        $url = Request::get('url') ?? "";
        $realUrl = '';
        $result = (new Vnil())->getItem($url);

        try{
            $sUrl = $result["video_info"]["url"];
            $realUrl = str_replace("https","http",$sUrl);
        }catch (\Exception $e){
            $realUrl = "";
        }
        return writeJson(200,$realUrl);


    }

    /*
    * 获取视频真实的播放地址
    * */
    public function getRealUrl(Request $request){
        $url = Request::get('url') ?? "";

        if(strpos($url,'xiaohongshuu') !== false){
            $note_id = str_replace("https://www.xiaohongshu.com/discovery/item/","",$url);
            $note_id = str_replace("http://www.xiaohongshu.com/discovery/item/","",$note_id);
            $realUrl = '';

            $content = (new Whosecard())->getDetailByNoteId($note_id);
            $result = json_decode($content,true);


            if($result["ok"]){
                try{
                    $sUrl = $result['result']['data'][0]['note_list'][0]['video']['url_info_list'][1]['url'];
                    $realUrl = str_replace("https","http",$sUrl);

                }catch (\Exception $e){
                    $content = (new Layzz())->getDetail($url);
                    $result = json_decode($content,true);
                    if($result["code"] == "0001"){
                        try{
                            $sUrl = $result["data"]["playAddr"];
                            $realUrl = str_replace("https","http",$sUrl);
                        }catch (\Exception $e){
                            $realUrl = "";
                        }
                    }
                    return writeJson(200,$realUrl);
                }
                return writeJson(200,$realUrl);
            }


        } else{
            $realUrl = '';
            $content = (new Layzz())->getDetail($url);
            $result = json_decode($content,true);

            if($result["code"] == "0001"){
                try{
                    $sUrl = $result["data"]["playAddr"];
                    $realUrl = str_replace("https","http",$sUrl);
                }catch (\Exception $e){
                    $realUrl = "";
                }
            }
//            $realUrl = '';
//            $result = (new Vnil())->getItem($url);
//
//
//
//
//            try{
//                $sUrl = $result["video_info"]["url"];
//                $realUrl = str_replace("https","http",$sUrl);
//            }catch (\Exception $e){
//                $realUrl = "";
//            }

            return writeJson(200,$realUrl);
        }

    }

    public function deal(Request $request)
    {
        $url = Request::get('url') ?? "";
        $appkey = "c22gv7jhjqq6yucjngme7q62";

        $param = [
            'appkey'	=> $appkey,
            'url'		=> $url,
        ];

        //得到请求的地址：https://api.vnil.cn/api/parse/deal?appkey=appkey&url=url

        $apiUrl = 'https://api.vnil.cn/api/parse/deal?'.http_build_query($param);

        $ch = curl_init();
        curl_setopt ( $ch, CURLOPT_URL, $apiUrl );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
        curl_setopt ( $ch, CURLOPT_MAXREDIRS, 5 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, 10 );
        $content = curl_exec( $ch );
        curl_close ( $ch);

        $result = json_decode($content,true);

        $data = $result["body"];
        return writeJson(200,$data);
    }



    public function total(){
        $sUrl = Request::get('url');
//        $url = "https://www.youwk.cn/api/sy/video&key=".$key.'&link='.$sUrl;
        $apiUrl = "https://www.youwk.cn/api/sy/video";
        $param = [
            "link" => $sUrl,
            "key" => "dcwkf5w1e3UvKhBGHm97uxoNOJ7Qac"
        ];
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        $output = curl_exec($ch);
        curl_close($ch);
        return writeJson(200,json_decode($output));
    }


    public function profile(){
        $sUrl = Request::get('url');
        $paging = Request::get('paging')??"";
        $url = "http://third.layzz.cn/lyz/batchAnalyseByPage";
        $data_string = [
            "link"=>$sUrl,
            "token"=>"nczzlk-ckc--auther-chenjw5470",
            "paging"=>$paging
        ];
        $res = $this->get_post_json($url,$data_string);
        return writeJson(200,json_decode($res));
    }


    public function newProfile(){
        $sUrl = Request::get('url');
        $paging = Request::get('paging')??"";
        $url = "https://qrcode.layzz.cn/test/ksBatchAnalyseByPage";
        $data_string = [
            "link"=>$sUrl,
            "token"=>"nczzlk-ckc--auther-chenjw5470",
            "paging"=>$paging
        ];
        $res = $this->get_post_json($url,$data_string);
        return writeJson(200,json_decode($res));
    }


    public function articleListall(){
        $params = Request::get();
        $app_id = $params['app_id']??"";
        $page = $params['page']??1;
        $article_type = $params['article_type']??"";
        $collection = $params['collection']??"";
        $app_token = \app\api\model\Account::where("app_id",$app_id)->value("app_token");
        $url = "https://baijiahao.baidu.com/builderinner/open/resource/query/articleListall";
        $data_string = [
            "app_token"=>$app_token,
            "app_id"=>$app_id,
            "page_no"=>$page,
        ];
        if (!empty($article_type)){
            $data_string["article_type"] = $article_type;
        }
        if (!empty($collection)){
            $data_string["collection"] = $collection;
        }
        if (!empty($params['start_time']) && !empty($params['end_time'])){
            $data_string["start_time"] = $params['start_time'];
            $data_string["end_time"] = $params['end_time'];
        }
        $res = $this->get_post_json($url,$data_string);
        return writeJson(200,json_decode($res));
    }


    private function get_post_json($url = '', $post_data = array()) {
        if (empty($url) || empty($post_data)) {
            return false;
        }
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
        curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-Type: application/json'));// 文本提交方式，必须声明请求头

        $data = curl_exec($ch);//运行curl
        if($data === false){
            var_dump(curl_error($ch));
        }else{
            curl_close($ch);
            return $data;
        }
    }

    function requestXhsData($cookie, $a1, $param, $api, $host, $authorization) {
        // 构造请求数据
        $data = [
            "a1" => $a1,
            "params" => $param,
            "method" => "post",
            "api" => $api,
        ];

        // 请求头
        $headers = [
            "Authorization: Token " . $authorization,
            "Content-Type: application/json",
        ];

        // 初始化 cURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $host . "/api/xhs/xs/");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 发送请求
        $response = curl_exec($ch);
        curl_close($ch);

        // 解析响应
        $responseData = json_decode($response, true);
        return $responseData['data'];
    }

    function requestXhsFeed($cookie, $param, $xsXt) {
        // 请求头
        $xhsHeader = [
            "accept: application/json, text/plain, */*",
            "accept-language: zh-CN,zh;q=0.9",
            "cache-control: no-cache",
            "content-type: application/json;charset=UTF-8",
            "origin: https://www.xiaohongshu.com",
            "pragma: no-cache",
            "referer: https://www.xiaohongshu.com/",
            "sec-ch-ua: \"Chromium\";v=\"112\", \"Google Chrome\";v=\"112\", \"Not:A-Brand\";v=\"99\"",
            "sec-ch-ua-mobile: ?0",
            "sec-ch-ua-platform: \"Windows\"",
            "sec-fetch-dest: empty",
            "sec-fetch-mode: cors",
            "sec-fetch-site: same-site",
            "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
            "cookie: " . $cookie,
            "X-s: " . $xsXt["X-s"],
            "X-t: " . $xsXt["X-t"],
        ];

        // 初始化 cURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://edith.xiaohongshu.com/api/sns/web/v1/feed");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $xhsHeader);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($param));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        // 发送请求
        $response = curl_exec($ch);
        curl_close($ch);

        // 解析响应
        return json_decode($response, true);
    }

    public function xhsDeal()
    {
        $params = Request::post();

        // 小红书帐号 cookie
//        $cookie = "gid=yYSY2KfyYWd2yYSY2Kfy8uqTdY1Th0YUju1uWxCDlJ6qCA28M1TTyk888y8qYJj8y0DqW22f; abRequestId=5e3a97ea-2df9-5e08-ab05-4f5012d20777; a1=19425b4366blzoanipt250f43wmlpprvqd1i9aj4z50000205086; webId=95b9aca6ad8d9ca1838d9610b96157e5; web_session=0400695299257e6d144ad3e7ff354be3c0c911; xsecappid=xhs-pc-web; webBuild=4.60.1; acw_tc=0a0bb4a317422912329798429ecdaf1ade73b9d337a06c2de38c2b48b0a913; unread={%22ub%22:%2267bf2cc4000000002902c74a%22%2C%22ue%22:%2267b1e02d000000001801b5c9%22%2C%22uc%22:25}; websectiga=2845367ec3848418062e761c09db7caf0e8b79d132ccdd1a4f8e64a11d0cac0d; sec_poison_id=366f6f7b-b6b7-4d6c-9157-8e5939e4326d; loadts=1742292706423";
        $cookie = $params["cookie"];
        // 小红书账号 cookie a1 字段
//        $a1 = "19425b4366blzoanipt250f43wmlpprvqd1i9aj4z50000205086";
        $a1 = $params["a1"];
        // 请求参数
        $param = [
//            "source_note_id" => "67c44556000000000302ba27",
            "source_note_id" => $params["source_note_id"],
            "image_formats" => ["jpg", "webp", "avif"],
            "extra" => ["need_body_topic" => "1"],
//            "xsec_token" => "ABi2vJCqzWCJFc7UtcJMprsD8u5fIJZiqKYmbVvnHdbtM=",
            "xsec_token" => $params["xsec_token"],
        ];
        // 请求 API
        $api = "/api/sns/web/v1/feed";
//        $api = "/api/xhs/notedetail";
        // 请求主机
        $host = "http://apiserver.top";
        // Authorization
        $authorization = "5f66009fe587a0241e7f442a01158f0df355c8d5";

        // 第一步：获取 X-s 和 X-t
        $xsXt = $this->requestXhsData($cookie, $a1, $param, $api, $host, $authorization);
//        print_r($xsXt);

        // 第二步：请求小红书 API
        $response = $this->requestXhsFeed($cookie, $param, $xsXt);
//        print_r($response);
        return $response;

    }

}
